<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="addList">
                            {{$ti18('rxList.newBtn',"新建")}}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{boentI18n('list.ChangeApplication','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button>
                                {{$ti18('rxList.moreBtn','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="doImport" v-if="findAuthRight('add')"><i
                                    class="iconfont icondaoru"></i>
                                    {{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportBtn','导出')}}
                                    </span>
                                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportSelected','导出选中')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('2')"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportResults','导出查询结果')}}
                                    </a-menu-item>
                                </a-sub-menu>
                                <a-menu-item @click="genHtml">
                                    <i class="iconfont icondaochu"></i>
                                    {{i18n('list.batchGen','批量生成')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="2"
                                    @click="editList()"
                                    v-if="findAuthRight('edit') && editEnable && selectedRowKeys.length > 0"
                                    alias="formRuleEdit"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn',"编辑")}}
                                </a-menu-item>
                                <a-menu-item
                                    key="3"
                                    @click="delByIds(selectedRowKeys)"
                                    v-if="findAuthRight('delete') && removeEnable && selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'danger'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="4"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>

                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                            {{$ti18('rxList.leachBtn','过滤')}}
                        </span>
                    </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="boentI18n('form.name','名称')">
                                    <a-input :placeholder="boentI18n('form.name','名称','input')"
                                             v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.key', '标识键')">
                                    <a-input :placeholder="i18n('form.key', '标识键','input')"
                                             v-model="queryParam.Q_KEY__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/core/formBoList/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10', '30', '40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="isGranted" slot-scope="{ text, record }">
                        <a-tag :color="statusMap[text].color">
                            <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="isLeftTree" slot-scope="{ text, record }">
                        <a-tag :color="statusMap[text].color">
                          <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }" :title="appIdName(text)">
                        {{allApps[text]? $i18(allApps[text].appName,'应用名称'): $ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="findAuthRight('edit') && editEnable" @click.stop="editList(record)">
                            {{$ti18('rxList.editBtn',"编辑")}}
                        </span>
                        <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id])">
                            {{$ti18('rxList.delBtn','删除')}}
                        </span>
                        <span @click.stop="preview(record)">
                            {{$ti18('rxList.previews','预览')}}
                        </span>
                        <span v-if="findAuthRight('add')" @click="copyList(record)">{{i18n('list.copy','复制')}}</span>
                        <span @click.stop="editHtml(record)">
                            {{i18n('list.editCode','编辑代码')}}</span>
                        <span @click.stop="deployMenu(record)" :title="$ti18('rxList.deployMenu','发布菜单')">
                            {{$ti18('rxList.deployMenu','发布菜单')}}
                        </span>
                        <span @click.stop="editHistory(record)">
                            {{$ti18('rxList.editHistory','历史记录')}}
                        </span>
                        <span @click.stop="searchMenus(record.id)" :title="$ti18('rxList.searchMenus','查看发布记录')">
                            {{$ti18('rxList.searchMenus','查看发布记录')}}
                        </span>
                        <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
            <a-modal :zIndex="99999" :title="i18n('msg.genPage','你确定要生成页面吗?')" v-model="remarkVisible" @ok="handleOk">
                <p>{{$ti18('rxForm.notes','备注')}}：</p>
                <br/>
                <p>
                    <a-textarea sty v-model="remark" :auto-size="{ minRows: 4}"></a-textarea>
                </p>
            </a-modal>
        </div>
    </rx-layout>
</template>

<script>
    import FormBoListApi from '@/api/form/core/formBoList';
    import FormBoListEdit from './FormBoListEdit'
    import FormImport from './FormImport'

    import {BaseList} from "@lowcode/jpaas-common-lib"
    import DialogBox from '../../../../assets/js/DialogBox'
    import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
    import {Util} from "@lowcode/jpaas-common-lib"
    import ListHistoryList from './ListHistoryList'
    import changeAppJs from "@/views/modules/share/changeApp";
    import {mapState} from "vuex";
    import exportApp from "@/views/modules/share/exportApp";
    import SysAppApi from "@/api/system/core/sysApp";
    import CopyFormBoList from "@/views/modules/form/core/CopyFormBoList";
    import AppSearch from "@/views/modules/share/AppSearch";
    import RxSearchApp from "@/views/modules/share/rx-search-app";
    import {openUrl} from "@/utils/util";
    import switchExport from "@/utils/switchExport";
    import ChartDataModelApi from "@/api/form/core/chartDataModel";
    import ChangeCategory from "@/views/modules/share/ChangeCategory.js"
    export default {
        name: 'FormBoListList',
        mixins: [BaseList, changeAppJs,AppSearch,switchExport,ChangeCategory],
        props:["currentApp"],
        components: {
            RxCategoryTreeeditor,
            FormImport,
            exportApp,
            RxSearchApp
        },
        computed: {
            ...mapState({
                //所属应用
                allApps: state => state.appSetting ? state.appSetting.allApps : {}
            }),
        },
        data() {
            return {
                columns: [
                    {
                        title: this.$ti18('rxList.index', '序号'),
                        type: 'indexColumn',
                        width: 60,
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'},
                    },
                    {
                        title: this.boentI18n('form.name', '名称'),
                        dataIndex: 'name',
                        sorter: true,
                        sortField: 'NAME_',
                        width: 200
                    },
                    {
                        title: this.$comi18('business.aliasKey', '标识键'),
                        dataIndex: 'key',
                        sorter: true,
                        sortField: 'KEY_',
                        width: 140
                    },
                    {
                        title: this.i18n('form.isGranted', '授权'),
                        dataIndex: 'isGranted',
                        width: 100,
                        scopedSlots: {customRender: 'isGranted'}
                    },
                    {
                        title: this.i18n('form.isLeftTree', '显示左树'),
                        dataIndex: 'isLeftTree',
                        width: 100,
                        scopedSlots: {customRender: 'isLeftTree'}
                    },
                    {
                        title: this.boentI18n('form.app', '所属应用'),
                        dataIndex: 'appId',
                        width: 100,
                        sortField: 'APP_ID_',
                        scopedSlots: {customRender: 'appId'}
                    },
                    {
                        dataIndex: 'isExport',
                        slots: {title: 'exportApp'},
                        width: 100,
                        scopedSlots: {customRender: 'isExport'}
                    },
                    {
                        title: this.$ti18('rxForm.createTime', '创建时间'),
                        dataIndex: 'createTime',
                        width: 130,
                        sorter: true,
                        sortField: 'CREATE_TIME_'
                    },
                    {
                        title: this.$ti18('rxList.action', '操作'),
                        dataIndex: 'action',
                        fixed: 'right',
                        scopedSlots: {customRender: 'action'},
                        width: 160
                    },
                ],
                component: FormBoListEdit,
                comment: this.i18n('list.comment', '系统自定义业务管理列表'),
                curTree: {},
                QueryData: {},
                statusMap: {
                    'YES': {color: 'green', text: this.$comi18('business.deleteMap.yes', '是')},
                    'NO': {color: 'blue', text: this.$comi18('business.deleteMap.no', '否')}
                },
                remarkVisible: false,
                remark: "",
                modal: this,
                statisticConfig: {
                    type: "static_form",
                    table: "FORM_BO_LIST t",
                    field: "TREE_ID_",
                    whereConf: [{name: "IS_DIALOG_", type: "string", dateFormat: "", op: "=", value: "NO"}]
                },
                /**
                 * 导出配置
                 */
                exportConf:{
                    Api:FormBoListApi,
                    id:"id"
                },
                //变更分类配置
                categoryConfig:{
                    Api:FormBoListApi,
                    catKey:"FORM",
                    gridRef:"table"
                },
                //选中左边树分类的id
                selectedTreeId:'',
            }
        },
        created() {
            this.isUserManager(this.$route.query.appId);
            this.queryParam.Q_IS_DIALOG__S_EQ = 'NO';
            this.needFilterAppId("isAppMenu");
            this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "formBoList", key);
            },
            i18n_2(name, text, key) {
                return this.$ti18(name, text, "formInvokeScript", key);
            },
            boentI18n(name, text, key) {
                return this.$ti18(name, text, "formBoEntity", key);
            },
            exportI18n(name, text, key) {
                return this.$ti18(name, text, "appExport", key);
            },
            //批量生成
            genHtml() {
                let self = this;
                var list = [];
                list = this.$refs.table.getSelectedRows();
                if (!list || list.length == 0) {
                    self.$warning({
                        title: self.$ti18('rxMsa.masWarn.delInfo', '警告'),
                        content: self.i18n('msg.selectGenRecord', '请选择需要导出的记录！'),
                    });
                    return;
                }
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips', '操作提示'),
                    zIndex: 20000,
                    content: this.i18n('msg.confirmGen', '您确定生成吗？'),
                    okText: this.$ti18('rxForm.ackBtn', '确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                    onOk() {
                        let solutionIds = []
                        list.forEach((item) => {
                            solutionIds.push(item.id)
                        })
                        return FormBoListApi.genHtml(solutionIds);
                    },
                    onCancel() {
                    }
                })

            },
            delById(ids) {
                return FormBoListApi.del({ids: ids.join(',')})
            },
            getListByParams(parameter) {
                parameter.params.Q_IS_DIALOG__S_EQ = 'NO' //查询为单据列表的数据
                let appId = this.curApp.appId;
                if (appId) {
                    parameter.params.Q_APP_ID__S_EQ = appId;
                }
                return FormBoListApi.query(parameter)
            },
            getAppQuery() {
                var query = {};
                if (this.curApp.appId) {
                    query.appId = this.curApp.appId;
                    query.appName = this.curApp.appName;
                }
                if(this.selectedTreeId && this.selectedTreeId!=0){
                    query.treeId = this.selectedTreeId
                }
                return query;
            },
            addList() {
                let dsAlias = "";
                if(this.currentApp && this.currentApp.dataSource){
                    dsAlias = JSON.parse(this.currentApp.dataSource).value;
                }
                let url= this.$router.resolve({
                    name: "FormBoListEdit",
                    query: {
                        isDialog: 'NO',
                        ...this.getAppQuery(),
                        dsAlias: dsAlias
                    }
                }).href;
                window.open(url);
            },
            editList(record) {
                if(!record){
                    let rows=this.$refs.table.getSelectedRows();
                    if(!rows || rows.length!=1){
                        this.$message.warning(this.i18n_2('content.isLine','"请选择一行!'));
                        return;
                    }
                    record = rows[0]
                }
                let obj={
                    name: "FormBoListEdit",
                    query: {
                        pkId: record.pkId,
                        isDialog: 'NO',
                        ...this.getAppQuery()
                    }
                };
                let url=this.$router.resolve(obj).href;
                let target="bolist_" + record.pkId;
                window.open(url,target);
            },
            //复制列表
            copyList(record) {
              var self_ = this;
              var config = {
                curVm: this,
                data: {record: record},
                component: CopyFormBoList,
                title: this.i18n("list.copyList",'列表复制')+'--' + record.name,
                widthHeight: ['750px', '450px'],
              }
              Util.open(config, function (action, data) {
                if (action != 'ok') {
                  return
                }
                FormBoListApi.copyNew(data).then((res) => {
                  self_.refreshGrid()
                })
              })
            },
            preview(record) {
                let appId=record.appId;
                let ctxPath= process.env.VUE_APP_CONTEXT_MAIN;
                let url=`${ctxPath}/list/${record.key}?appId=${appId}`;
                let title=record.name;
                openUrl({url:url,title:title,curVm:this,max:true});
            },
            editHtml(record) {
                DialogBox.editHtml(record.id, {
                    curVm: this,
                    max: true,
                }, this.showModal)
            },
            showModal(self) {
                if (self) {
                    this.modal = self;
                }
                this.remark = "";
                this.remarkVisible = true;
            },
            handleOk() {
                this.remarkVisible = false;
                if (this.modal && this.modal.saveHtml) {
                    this.modal.saveHtml(this.modal, this.remark);
                }
            },
            deployMenu(record) {
                var component = 'modules/form/FormBoListPreview/FormBoListPreview.vue';
                DialogBox.openDeploymenuDialog(
                    {
                        curAppObj:this.curApp,
                        releaseId: record.id,
                        name: record.name,
                        key: record.key + 'List',
                        boListId: record.id,
                        boListKey: record.key,
                        component: component,
                        settingType: "custom",
                        params: {listKey: record.key},
                    },
                    {
                        curVm: this,
                        widthHeight: ['800px', '600px'],
                    }
                )
            },
            searchMenus(releaseId) {
                var config = {
                    curVm: this,
                    data: {
                        releaseId: releaseId,
                    },
                }
                DialogBox.openMenuReleaseDialog(config)
            },
            editHistory(record) {
                var config = {
                    curVm: this,
                    data: {listId: record.id, keyId: record.key},
                    component: ListHistoryList,
                    title: this.i18n('list.changeHis', '列表变更历史记录') + '--' + record.name,
                    max: true,
                }
                Util.open(config)
            },
            handSelect(curRow) {
                this.curTree = curRow
                var treeId = curRow.treeId;
                this.selectedTreeId = treeId;
                let params = {
                    Q_IS_DIALOG__S_EQ: "NO",
                    Q_TREE_ID__S_EQ: ""
                }
                if (treeId != "0") {
                    params.Q_TREE_ID__S_EQ = treeId;
                } else {
                    params.Q_TREE_ID__S_EQ = "";
                }
                this.loadData(params)
            },
            search() {
                this.$refs.table.loadData();
            },
            cancel() {
                this.$nextTick(() => {
                    this.queryParam = {};
                    this.queryParam.Q_IS_DIALOG__S_EQ = 'NO';
                    let appId = this.curApp.appId;
                    if (appId) {
                        this.queryParam.Q_APP_ID__S_EQ = appId;
                    }
                    this.$nextTick(() => {
                        this.$refs[this.table].loadData();
                    })
                })
            },
            closeSearchbar() {
                //关闭过滤弹窗；（点击X触发）
                this.fitSearch = false;
            },
            doExport(isSelected) {
                let self = this;
                var exportList = [];
                //选中的导出
                if (isSelected == "1") {
                    exportList = this.$refs.table.getSelectedRows();
                    if (!exportList || exportList.length == 0) {
                        self.$warning({
                            title: self.$ti18('rxMsa.masWarn.delInfo', '警告'),
                            content: self.i18n('msg.selectRecord', '请选择需要导出的记录！'),
                        });
                        return;
                    }
                    let solutionIds = []
                    exportList.forEach((item) => {
                        solutionIds.push(item.id)
                    })
                    this.QueryData.params = {
                        ids: solutionIds.toString()
                    }
                } else {
                    // 导出所查询的
                    this.QueryData.params = {
                        isQuery: 0,
                    }
                    this.QueryData.params = Object.assign(this.QueryData.params, this.queryParam)
                }
                if (this.$refs.table.dataAction == "") {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                        content: this.i18n('msg.noData', '该分类没有数据！'),
                    });
                    return;
                }
                FormBoListApi.listExport(this.QueryData)
            },
            doImport() {
                if (!this.curTree || !this.curTree.treeId) {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                        content: this.i18n('msg.selectCat', '请选择表分类！'),
                    });
                    return
                }
                var treeId = this.curTree.treeId
                Util.open(
                    {
                        component: FormImport,
                        curVm: this,
                        widthHeight: ['800px', '600px'],
                        title: this.i18n('list.listImport', '数据列表导入'),
                        data: {
                            treeId: treeId,
                            callback: function (params) {
                                let self = this;
                                FormBoListApi.doImport(params).then(res => {
                                    this.isSpinning = false;
                                    if (!res.success) {
                                        self.$confirm({
                                            title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                                            zIndex: 20000,
                                            content: this.$comi18('SysApp.appImport.importFailed', '导入失败！'),
                                            okText: this.$ti18('rxForm.ackBtn', '确认'),
                                            cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                                        });
                                        return;
                                    }
                                    self.getUpdataSqls(res.data);
                                });
                            }
                        }
                    }, function (action) {
                    });
            },
            changeAppId(selectedRows) {
                FormBoListApi.saveList(selectedRows);
            },
            appIdName(text){
                return this.allApps[text]? this.$i18(this.allApps[text].appName,'应用名称'): this.$ti18('rxList.noAppName','无')
            }

        },
    }
</script>
<style scoped>

</style>

